package btree;

import java.util.Stack;

public class Demo1 {
    public static void main(String[] args) {
        new Demo1().test();
    }

    public void test() {
        Node<String> root =
            new Node<>("a")
                .setLeft(new Node<>("b")
                    .setLeft(new Node<>("c")
                        .setLeft(new Node<>("d")
                            .setRight(new Node<>("g"))))
                    .setRight(new Node<>("e")))
                .setRight(new Node<>("f"));
        String[] list = viewBTree(root);
    }

    public <T> T[] viewBTree(Node<T> root) {
        Stack<Node<T>> s = new Stack<>();
        Node<T> p = root;
        do {
            showSequence(p);

            if (p.left != null) {
                s.add(p);
                p = p.left;
                continue;
            }
            if (p.right != null) {
                p = p.right;
                continue;
            }
            Node<T> top = null;
            while (!s.empty() && (top = s.pop()) != null && top.right == null) {
            }
            if (top == null) {
                break;
            }
            p = top.right;
        } while (true);
        return null;
    }

    public <T> void showSequence(Node<T> p) {
        while (p != null) {
            System.out.print(p.data);
            p = p.parent;
        }
        System.out.println();
    }

    class Node<T> {
        public T data;
        public Node<T> left;
        public Node<T> right;
        public Node<T> parent;

        public Node<T> setLeft(Node<T> node) {
            this.left = node;
            return this;
        }
        public Node<T> setRight(Node<T> node) {
            this.right = node;
            return this;
        }

        public Node(){}
        public Node(T data){
            this.data = data;
        }
    }
}
